package com.fangyi.yunmusic.service.impl;

import com.fangyi.yunmusic.config.ResourceConfig;
import com.fangyi.yunmusic.exception.YunMusicException;
import com.fangyi.yunmusic.mapper.*;
import com.fangyi.yunmusic.pojo.Comment;
import com.fangyi.yunmusic.pojo.CommentLike;
import com.fangyi.yunmusic.pojo.Playlist;
import com.fangyi.yunmusic.pojo.User;
import com.fangyi.yunmusic.pojo.front.end.FECommentVO;
import com.fangyi.yunmusic.pojo.vo.CommentVO;
import com.fangyi.yunmusic.pojo.vo.UserVO;
import com.fangyi.yunmusic.service.CommentService;
import com.fangyi.yunmusic.service.notification.CommentNotificationService;
import com.fangyi.yunmusic.service.utils.MapConvertUtils;
import com.fangyi.yunmusic.service.utils.VOConvertUtils;
import com.fangyi.yunmusic.utils.FileServerUtils;
import com.fangyi.yunmusic.utils.PagedResult;
import com.fangyi.yunmusic.utils.PojoUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.n3r.idworker.Id;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

import static com.fangyi.yunmusic.constant.CommentTypeConstant.ALBUM;
import static com.fangyi.yunmusic.constant.CommentTypeConstant.SONG;
import static com.fangyi.yunmusic.constant.CommentTypeConstant.SONGLIST;
import static java.util.stream.Collectors.toList;
@Service
public class CommentServiceImpl implements CommentService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private SongMapper songMapper;
    @Autowired
    private PlaylistMapper playlistMapper;
    @Autowired
    private AlbumMapper albumMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private CommentLikeMapper commentLikeMapper;
    @Autowired
    private ResourceConfig resourceConfig;
    @Autowired
    private VOConvertUtils voConvertUtils;

    @Autowired
    private CommentNotificationService commentNotificationService;

    @Override
    public List<CommentVO> getNotReadComments(String userId) {
        Set<String> commentIds = commentNotificationService.getAll(userId);
        List<CommentVO> comments = new ArrayList<>();
        commentIds.forEach(commentId -> {
            CommentVO commentVO = new CommentVO();
            Comment comment = commentMapper.selectByPrimaryKey(commentId);
            PojoUtils.copyProperties(comment, commentVO);
            User user=userMapper.selectByPrimaryKey(comment.getUserId());
            UserVO userVO =voConvertUtils.convertToUserVO(user);
            commentVO.setUserVO(userVO);
            commentVO.setCommentLikeCount(getCommentLikeCount(comment.getId()));

            if (comment.getType() == SONGLIST) {
                Playlist playlist = playlistMapper.selectByPrimaryKey(comment.getTargetId());
                CommentVO.Target target = new CommentVO.Target();
                target.setTargetId(playlist.getId());
                target.setTargetName(playlist.getName());
                commentVO.setTarget(target);
            }
            comments.add(commentVO);
        });
        return comments;
    }

    @Override
    public List<String> getUserIdsFromCommentTarget(FECommentVO feCommentVO) {
        List<String> ids = new ArrayList<>();
        if (feCommentVO.getType() == SONGLIST) {
            String playlistId = feCommentVO.getTargetId();
            Playlist playlist = playlistMapper.selectByPrimaryKey(playlistId);
            if (playlist != null) {
                ids.add(playlist.getUserId());
            }
        }
        return ids;
    }

    @Override
    public void publishComment( FECommentVO feCommentVO) {
        System.out.println(feCommentVO.getUserId());
        if(userMapper.selectByPrimaryKey(feCommentVO.getUserId())==null)
            throw new YunMusicException("用户id不存在！");
        switch (feCommentVO.getType()){
            case SONG:{
                if(songMapper.selectByPrimaryKey(feCommentVO.getTargetId())==null)
                    throw new YunMusicException("歌曲id不存在");
                break;
            }
            case SONGLIST:{
                if(playlistMapper.selectByPrimaryKey(feCommentVO.getTargetId())==null)
                    throw new YunMusicException("歌单id不存在");
                break;
            }
            case ALBUM:{
                if(albumMapper.selectByPrimaryKey(feCommentVO.getTargetId())==null)
                    throw new YunMusicException("专辑id不存在");
                break;
            }
            default:
                throw new YunMusicException("评论类型不正确");
        }
        if(!(feCommentVO.getContent().length()>0))
            throw new YunMusicException("评论为空！");
        if(feCommentVO.getReplyCommentId()!=null&&commentMapper.selectByPrimaryKey(feCommentVO.getReplyCommentId())==null)
            throw new YunMusicException("被回复的评论ID不存在！");
        Comment comment=new Comment();
        comment.setId(Id.nextString());
        BeanUtils.copyProperties(feCommentVO,comment);
        comment.setCreateTime(new Date());
        commentMapper.insert(comment);

        // 添加通知到redis
        if (feCommentVO.getType() == SONGLIST) {
            String playlistId = feCommentVO.getTargetId();
            Playlist playlist = playlistMapper.selectByPrimaryKey(playlistId);
            if (playlist != null) {
                commentNotificationService.add(playlist.getUserId(), comment.getId());
            }
        }
    }

    @Override
    public void deleteComment(String commentId) {
        System.out.println(commentId);
        if(commentMapper.selectByPrimaryKey(commentId)==null)
            throw new YunMusicException("评论id不存在！");
        commentMapper.deleteByPrimaryKey(commentId);
    }

    @Override
    public PagedResult selectCommentVO(int pageNum, int pageSize, int type,String targetId) {
        PageHelper.startPage(pageNum,pageSize);
        List<Comment> commentLists=null;
        switch(type){
            case SONG:{
                commentLists=commentMapper.selectSongComment(targetId);
                break;
            }
            case SONGLIST:{
                commentLists=commentMapper.selectPlaylistComment(targetId);
                break;
            }
            case ALBUM:{
                commentLists=commentMapper.selectAlbumComment(targetId);
                break;
            }
        }
//        List<Comment> commentLists=commentMapper.selectAll();
        PageInfo<?> pageInfo=new PageInfo<>(commentLists);
        int pages=pageInfo.getPages();
        long total=pageInfo.getTotal();
//        List<String> userIds=getUserIdsFromCommentLists(commentLists);
//        List<User> users=null;
//        if(users.size()>0)
//            userMapper.selectUserByIds(userIds);
//
//        Map<String,User> userMap=MapConvertUtils.convertToUserMap(users);
        List<CommentVO> commentVOS=convertToCommentVOs(commentLists);
        return new PagedResult(commentVOS,pageNum,pages,total);
    }

    @Override
    public void commentLike(String userId, String commentId) {
        if(userMapper.selectByPrimaryKey(userId)==null)
            throw new YunMusicException("用户id不存在！");
        if(commentMapper.selectByPrimaryKey(commentId)==null)
            throw new YunMusicException("评论id不存在！");
//        Example example=new Example(CommentLike.class);
//        Example.Criteria criteria=example.createCriteria();
//        criteria.andEqualTo("userId",userId).andEqualTo("commentId",commentId);
//        if(commentLikeMapper.selectByExample(example)!=null)
//            throw new YunMusicException("已点赞！");
        if(iscommentLiked(userId,commentId))
            throw new YunMusicException("已点赞！");
        CommentLike commentLike=new CommentLike();
        commentLike.setId(Id.nextString());
        commentLike.setUserId(userId);
        commentLike.setCommentId(commentId);
        commentLikeMapper.insert(commentLike);
    }

    @Override
    public void discommentLike(String userId, String commentId) {
        if(userMapper.selectByPrimaryKey(userId)==null)
            throw new YunMusicException("用户id不存在！");
        if(commentMapper.selectByPrimaryKey(commentId)==null)
            throw new YunMusicException("评论id不存在！");
        if(iscommentLiked(userId,commentId)==false)
            throw new YunMusicException("未点赞！");
        Example example=new Example(CommentLike.class);
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("userId",userId).andEqualTo("commentId",commentId);
        commentLikeMapper.deleteByExample(example);
    }

    public boolean iscommentLiked(String userId,String commentId){
        Example example=new Example(CommentLike.class);
        Example.Criteria criteria=example.createCriteria();
        criteria.andEqualTo("userId",userId).andEqualTo("commentId",commentId);
        if(commentLikeMapper.selectByExample(example).size()==1)
            return true;
        else return false;
    }

    @Override
    public int getCommentLikeCount(String commentId) {
        return commentLikeMapper.getCommentLikeCount(commentId);
    }

    private List<String> getUserIdsFromCommentLists(List<Comment> commentLists) {
        return commentLists.stream().map(Comment::getUserId).collect(toList());
    }


    private List<CommentVO> convertToCommentVOs(List<Comment> commentList){
        return commentList.stream().map( comment->{
                    CommentVO commentVO=convertToCommentVO(comment);
//            BeanUtils.copyProperties(comment,commentVO);
//            User user=userMap.get(comment.getUserId());
//            UserVO userVO =VOConvertUtils.convertToUserVO(user);

//            BeanUtils.copyProperties(user, userVO);
//            userVO.setAvatarImgUrl(FileServerUtils.getUserAvatarUrl(resourceConfig.getFileServer(), user.getId()));
//            commentVO.setUserVO(userVO);
//            commentVO.setCommentLikeCount(getCommentLikeCount(comment.getId()));
            String replyCommentId=comment.getReplyCommentId();
            if(replyCommentId==null)
                return commentVO;
            Comment replyComment=commentMapper.selectByPrimaryKey(replyCommentId);
            if(replyComment!=null){
                CommentVO replyCommentVO=convertToCommentVO(replyComment);
                commentVO.setReplyComment(replyCommentVO);
            }

            return commentVO;
                }

        ).collect(toList());

    }

    /**
     *
     * @param comment
     * @return 返回的CommentVO尚未对replyCommentVO赋值
     */
    private CommentVO convertToCommentVO(Comment comment){
        CommentVO commentVO=new CommentVO();
        BeanUtils.copyProperties(comment,commentVO);
        User user=userMapper.selectByPrimaryKey(comment.getUserId());
        UserVO userVO =voConvertUtils.convertToUserVO(user);
        commentVO.setUserVO(userVO);
        commentVO.setCommentLikeCount(getCommentLikeCount(comment.getId()));
        return commentVO;
    }
}
